import Vue from 'vue'
import Router from 'vue-router'
import { constantRouterMap } from './routers'
import store from '../store'
import ViewUI from 'view-design'
import { setDocumentTitle } from '@/utils/util'
import { ACCESS_TOKEN } from '@/store/mutation-types'

const whiteList = ['login', 'register', 'registerResult']

Vue.use(Router)

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRouterMap
})

router.beforeEach((to, from, next) => {
  ViewUI.LoadingBar.start()
  to.meta && (typeof to.meta.title !== 'undefined' && setDocumentTitle(`${to.meta.title}`))
  if (Vue.ls.get(ACCESS_TOKEN)) {
    /* has token */
    if (to.path === '/user/login') {
      next({ path: '/home' })
      ViewUI.LoadingBar.finish()
    } else {
      if (store.getters.addRouters.length === 0) {
        store.dispatch('GetInfo')
          .then(res => {
            store.dispatch('GenerateRoutes', res).then(() => {
              // 根据roles权限生成可访问的路由表
              // 动态新增可访问路由表
              router.addRoutes(store.getters.addRouters)
              const redirect = decodeURIComponent(from.query.redirect || to.path)
              if (to.path === redirect) {
                // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                next({ ...to, replace: true })
              } else {
                // 跳转到目的路由
                next({ path: redirect })
              }
            })
          }).catch((e) => {
            store.dispatch('Logout').then(() => {
              next({ path: '/user/login', query: { redirect: to.fullPath } })
            })
          })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.name)) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next({ path: '/user/login', query: { redirect: to.fullPath } })
      ViewUI.LoadingBar.finish()
    }
  }
})

router.afterEach(() => {
  ViewUI.LoadingBar.finish()
})

export default router
